<template>
	<view class="content">
		<!-- 404页面 -->
		<view class="noData" v-if="netWorkType == 'none'">
			<noData @handle="refresh"></noData>
		</view>
		<view v-if="netWorkType != 'none'">
			<tui-skeleton v-if="skeletonShow" backgroundColor="#fafafa" borderRadius="10rpx"></tui-skeleton>
			<view class="container tui-skeleton">

				<view class="cpt-mask" v-if="showMaskloading">
					<view class="mask-tip">
						<view style="display: flex;justify-content: center;">
							<image src="https://xoimg.aiouning.com/static/cash_loading.gif"
								style="width:120rpx;height: 120rpx;"></image>
						</view>
						<view class="txt">连接设备中,请耐心等待...</view>

						<tui-tag @tap="cancelConn()" style="position: relative; z-index: 99999999;" shape="circle"
							type="theme-blue">取消连接</tui-tag>
					</view>

				</view>
				<!-- 头部	 开始-->
				<view class="head-box marginleft15 marginright15">

					<view class="flex-box">
						<view class="head-list">
							<view v-if="data.userInfo.bindStatus&&JSON.stringify(data.check)!='{}'"
								class="bg-white padright15 border-radius8 padbottom5"
								style="margin-bottom: 24rpx;padding-left: 26rpx;">

								<view class="time">
									<view class="lf">{{data.check.create_time}}</view>
									<!-- <view class="rg">
										
									</view> -->
								</view>
								<view class="data-box   ">
									<view class="lf">
										<view class="word">{{data.check.glu}}</view>
									</view>
									<view class="rg">
										<view>
											<tui-tag v-if="data.check.status==1" size="small" padding="12rpx"
												type="green">正常</tui-tag>
											<tui-tag v-if="data.check.status==2" size="small" padding="12rpx"
												type="danger">低血糖</tui-tag>
											<tui-tag v-if="data.check.status==3" size="small" padding="12rpx"
												type="danger">高血糖</tui-tag>
										</view>
										<view class="word">
											{{data.check.unit_type_desc?data.check.unit_type_desc:''}}
										</view>

									</view>


								</view>
							</view>
							<view v-else class="bg-white padright15 border-radius8 padbottom15"
								style="margin-bottom: 24rpx;padding-left: 26rpx;">
								<view class="data-box  padtop10">
									<view class="lf">
										<view style="color:#6F6F6F;" class="word">- -</view>
									</view>

								</view>
							</view>
						</view>
						<view style="margin-top: 60rpx;">
							<tui-tag v-if="data.userInfo.bindStatus&&connected" shape="circle" type="theme-blue">已连接
							</tui-tag>
							<view v-if="!data.userInfo.bindStatus&&data.userInfo.deviceId!=''"
								:data-device-id="data.userInfo.deviceId" data-name="自动连接" @tap="autoConn()">
								<tui-tag shape="circle" type="theme-blue">连接设备</tui-tag>
							</view>
							<!--   @tap="checkBind($event)"    -->
							<view v-if="data.userInfo.bindStatus&&data.userInfo.deviceId!=''&&!connected"
								:data-device-id="data.userInfo.deviceId" data-name="自动连接" @tap="autoConn()">
								<!-- <tui-tag     shape="circle" type="theme-gray">设备断开</tui-tag> -->
								<tui-tag shape="circle" type="theme-blue">连接设备</tui-tag>
							</view>
							<view v-if="!data.userInfo.bindStatus&&data.userInfo.deviceId==''" @tap="searchDev()">
								<tui-tag shape="circle" type="theme-blue">连接设备</tui-tag>
							</view>

						</view>

					</view>

				</view>

				<!-- 头部	 结束-->
				<!--测试结果反馈	 开始-->
				<view class="res-box marginleft15 marginright15">
					<view class="flex-box margin-bottom20">
						<view class="item">
							<view class="font16 font-bold margin-bottom5">数据分析</view>

						</view>
						<view class="item" @tap="testResult">

							<view class="iconfont font14  word">
								&#xe6c1;测试说明
							</view>

						</view>
					</view>
					<view class="flex-box margin-bottom20 bg">
						<view class="res-list">
							<view class="border-radius8 pd">
								<view v-if="data.check.status==1" class="title">
									该成员今日测试数据正常,请继续保持良好的生活习惯,坚持做测试
								</view>
								<view v-else-if="data.check.status==2" class="title">
									该成员今日测试数据血糖偏低,请及时到医院检查
								</view>
								<view v-else-if="data.check.status==3" class="title">
									该成员今日测试数据血糖偏高,请及时到医院检查
								</view>
								<view v-else class="title">
									你暂未检测血糖数据
								</view>
							</view>

						</view>


					</view>
				</view>
				<!-- 测试结果反馈	 结束-->




				<!--图表	 开始-->
				<view class="week-trend  padbottom15 bg-white padtop15">
					<view class="flex-box padleft15 padright15">
						<text class="font16 font-bold">血糖波动趋势</text>
						<view>
							<!-- <text class="circle-icon margin-right5"></text> <text class="font12" font12>高压</text>
						<text class="circle-icon low margin-right5 marginleft15"></text> <text class="font12">低压</text> -->
						</view>
						<view class="viewMore font12 text-center" @tap="testRecord">

							<view>
								<text class="font14 font-gray2">查看更多数据</text>
								<text class="iconfont padleft5 font12 font-gray">&#xe62b;</text>
							</view>
						</view>
					</view>
				 
					<view class="echart-view" v-if="showEchart"  >
						<view class="f2_container ">
							 <canvas  type="2d" class="f2-canvas"    @touchStart="touchStart" @touchMove="touchMove" @touchEnd="touchEnd" />
						</view>
						<!-- <view class="line_chart">

							<canvas :canvasId="canvasId" id="canvasId" disable-scroll="true"
								:style="{ width: cWidth + 'px', height: cHeight + 'px','zindex':1 }"
								@touchstart="touchstart" @touchmove="touchmove" @touchend="touchend" />
							<slot />
						</view> -->
					</view>
					<!-- <view class="viewMore font12 text-center"  v-if="showEchart">
					<view class="btn  pad-all10 bg-body2 font-white" @tap="moreData">查看更多数据</view>
				</view> -->
				</view>
				<!-- 图表		 结束-->
				<!--文章	 开始-->

				<view class="relate-prod-list">
					<view class="flex-box font16 padbottom15 padleft15 padright15 font-bold padtop30"
						style="padding-left: 5px;">

						<!-- <view style="width:4px;height:20px;background-color:#3894FF;"></view> -->
						<view style="border-left: 4px solid #3894FF;padding-left: 15px; margin-left: -5px;">文章推荐</view>

						<view @tap="pageArticleList">
							<text class="font14 font-gray2">查看更多</text>
							<text class="iconfont padleft5 font12 font-gray">&#xe62b;</text>
						</view>
					</view>

					<view class="box bg-white marginleft15 marginright15 pad-all10 p-relative"
						v-for="(item,index) in data.article">
						<view class="flex-start-box" @click="articleDetail(item.id)">
							<view class="flex-item" style="flex-grow: 1;">
								<view class="title font12">
									{{item.title}}
								</view>
								<view style="position: absolute;bottom: 20rpx;display: flex;">
									<!-- <view class="font10 padtop10 padbottom5 font-gray" style="margin-top: 10rpx;">{{item.author}}</view> -->
									<view class="font10 font-gray">
										{{item.view_count}}人看过
									</view>
									<view class="font10 font-gray marginleft15">
										{{item.praise_num}}人点赞
									</view>
								</view>

							</view>
							<view class="right-img flex-item">
								<image :src="item.image"></image>
							</view>

						</view>
					</view>
				</view>
				<!-- 文章		 结束-->



			</view>

		</view>
		<uni-popup ref="conn" type="bottom" :bg="false" :custom="true">
			<view :style="{height:windowHeight,'margin-bottom':mBottom}" class="conn-box">

				<view class="flex-box">
					<view v-if="connStatus==0||connStatus==1" class="conn-list">
						<view style="text-align: center;color:#4299FF;font-size:60rpx;" class="iconfont  margintop10">
							&#xe737;</view>
						<view style="font-size:30rpx; text-align: center;" class="margintop10">正在搜索附近的蓝牙设备...</view>
						<view class="img">
							<!-- <image :src="OSS_HOST+'ble_search.gif'" ></image> -->
						</view>
					</view>
					<view v-if="connStatus>=2&&connStatus<30" style="margin-top: 150rpx;" class="conn-list">

						<view class="img2" v-if="connStatus==8">
							<image :src="OSS_HOST+'no_dev.png'"></image>
						</view>
						<view class="margintop10 word">{{errorMsg[connStatus].msg}}</view>
						<view class="margintop10 word1">{{errorMsg[connStatus].code}}</view>
						<view class="reconn">

							<tui-tag v-if="errorMsg[connStatus].connType=='create'" @tap="openBluetoothAdapter"
								shape="circle" type="theme-blue">再次连接</tui-tag>
								
							<view v-if="errorMsg[connStatus].connType=='reconnect' && rebind"
								:data-device-id="data.userInfo.deviceId"  data-conn="bind" data-name="自动连接" @tap="checkBind($event)">
								<tui-tag shape="circle" type="theme-blue">
									重新连接
								</tui-tag>
							
							</view>	
							<!-- 只绑定一个设备则直接重连不弹出设备选择窗 -->
							<view v-if="errorMsg[connStatus].connType=='reconnect' && bindDdevNum==1 && !rebind"
								:data-device-id="data.userInfo.deviceId" data-name="自动连接" @tap="autoConn($event)">
								<tui-tag shape="circle" type="theme-blue">
									重新连接
								</tui-tag>

							</view>
							<!-- 已绑定多个设备则走这个重连 弹出设备选择窗 -->
							<view v-if="errorMsg[connStatus].connType=='reconnect' && bindDdevNum>1 && !rebind"
								  data-name="自动连接" @tap="showBindChangeDev">
								<tui-tag shape="circle" type="theme-blue">
									重新连接
								</tui-tag>
							
							</view>

						</view>
						<view @tap="searchDev()"
							style="font-size: 28rpx; color:#82B5FF; text-align: center; margin-top: 40rpx;">重新获取蓝牙设备
						</view>
					</view>

					<view v-if="connStatus>=30" style="margin-top: 150rpx;" class="conn-list">

						<view class="img1">
							<image :src="OSS_HOST+'glu_measure.gif'"></image>
						</view>
						<view class="margintop10 word">{{errorMsg[connStatus].msg}}</view>
						<view class="margintop10 word1">{{errorMsg[connStatus].code}}</view>
						<view class="reconn">

							<tui-tag v-if="errorMsg[connStatus].connType=='create'" @tap="openBluetoothAdapter"
								shape="circle" type="theme-blue">再次连接</tui-tag>
						</view>
					</view>

				</view>
				<view v-if="connStatus==1" style="position:absolute;bottom:80rpx;width: 100%;" class="flex-box">
					<view class="conn-dev-list marginleft15 marginright15">

						<view class="bg-white border-radius8 pd">
							<scroll-view class="device_list" scroll-y scroll-with-animation>
								<view v-for="(item, index) in devices" :key="index" class="main-box">
									<!-- style="padding-top: 0px;" -->
									<view class="lf">{{ item.name }}</view>
									<view :data-device-id="item.deviceId" data-conn="bind" :data-name="item.name || item.localName"
										@tap="checkBind($event)" class="rg">
										<tui-tag margin="20rpx 20rpx 0 0" plain type="black">连接</tui-tag>
									</view>
								</view>

							</scroll-view>

						</view>

					</view>

				</view>
			</view>
		</uni-popup>
		
		<!-- 选择设备提示窗 -->
		<uni-popup id="bindChangeDev" ref="bindChangeDev" type='center' @change="popupChange()">
			<view class="self-dialog" style="background: white;width: 90%;">
				<view class="title">
					请选择设备
				</view>
				<view class="flex-start-box box-item" :class="{ 'dev-select': isUa }" v-if="bindDevList.sinocare[4].mac!=undefined"  @tap="ChangeDev(4)" style="background:#eef3f8;border-radius: 20rpx;height: 120rpx;">
		
					<view class="equip-img border-radius4" style="width: 100rpx;height: 100rpx;padding-left: 10rpx;">
						<image src="http://img.aiouning.com/uploader/upload/202110/29/20211029111259617b66bbbbfbd.png" class="publicImg" mode="widthFix"></image>
					</view>
					<view>
						<view class="title padleft5 dev-item">
							<text class="over-ellipsis-two">三诺血糖尿酸仪 UG-11蓝牙</text>
		
						</view>
					</view>
		
				</view>
				<view class="flex-start-box box-item"  :class="{ 'dev-select': isGlu }"  v-if="bindDevList.sinocare[3].mac!=undefined" @tap="ChangeDev(3)" style="background:#eef3f8;margin-top: 20rpx;border-radius: 20rpx;height: 120rpx;" >
					<view class="equip-img border-radius4" style="width: 100rpx;height: 100rpx;padding-left: 10rpx; ">
						<image src="http://img.aiouning.com/uploader/upload/202110/29/20211029111257617b66b93e006.png" class="publicImg" mode="widthFix"></image>
					</view>
					<view>
						<view class="title  padleft5 dev-item" >
							<text class="over-ellipsis-two">三诺血糖仪 安稳+Air</text>
		
						</view>
					</view>
		
				</view>
				<view class="flex-start-box box-item"  :class="{ 'dev-select': isMyCuia }"  v-if="bindDevList.mycuia.mac!=undefined" @tap="ChangeDev(2)" style="background:#eef3f8;margin-top: 20rpx;border-radius: 20rpx;height: 120rpx;" >
					<view class="equip-img border-radius4" style="width: 100rpx;height: 100rpx;padding-left: 10rpx; ">
						<image src="http://img.aiouning.com/uploader/upload/202112/09/2021120909550461b161f8636ae.png" class="publicImg" mode="widthFix"></image>
					</view>
					<view>
						<view class="title  padleft5 dev-item" >
							<text class="over-ellipsis-two">民康血糖仪 MK-ZY 801</text>
						
						</view>
					</view>
						
				</view>
				<view class="flex-start-box box-item"  style="margin-top: 64rpx;">
					<view style="width: 50%;">
						<button class="mini-btn"  type="primary" style="background-color:#979797;color:#fff;border: 0rpx;width: 200rpx;" @click="connel()" >取消</button>
					</view>
					 <view style="width: 50%;">
						 <button class="mini-btn"  type="primary"  style="background-color:#3894ff;color:#fff;border: 0rpx;width: 200rpx;" @click="commit()" >确认</button>
		
					 </view>
		
				</view>
		
		
			</view>
		
		</uni-popup>
		
		<uni-popup ref="show" type="center">
			<uni-popup-dialog titleCss="remind" title="连接失败" content="请重新保持设备常亮,重新搜索设备并连接" :isClose="false"
				@confirm="confirm"></uni-popup-dialog>
		</uni-popup>
	</view>

</template>

<script>
	import {oss_host} from '@/config/config.js';
	var { DevComm } = require('@/js_sdk/blood/gochek/microtech-devicecomm.min.js');
	const microtechDevComm = DevComm.init();
	import Vue from 'vue'
	import {
		fail
	} from 'assert';
	import store from '@/store/index.js';
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'
	// 骨架屏
 
	import tuiSkeleton from "@/components/tui-skeleton/tui-skeleton"
	import tuiTag from '@/components/tag/tag'
	import blood from '@/utils/dev/blood/blood.js'
	import F2 from '@/js_sdk/uni-f2/f2.min.js'
	import utils from "../../../../utils/sannuo.js";
	var app = getApp();
	
	function wrapEvent(e) {
	  if (!e) return
	  if (!e.preventDefault) {
	    e.preventDefault = function() {}
	  }
	  return e
	}
	let chart = null
	const lineCharts = {},
		optionAs = {};
	import {
		mapGetters
	} from 'vuex';
	export default {
		components: {
			tuiSkeleton,
			tuiTag,
			// LineChart,
			uniPopup,
			uniPopupDialog
		},
		data() {
			return {
				echartsData:[],
				mBottom: '0px',
				OSS_HOST: oss_host,
				data: {
					article: [],
					userInfo: {
						bindStatus: false,
						deviceId: ''
					},
					check: {}
					
				},
				bindDevList:[], //已绑定的设备
				bindDdevNum:0, //已绑定设备数量
				isAutoConn: false,
				//设备id
				deviceId: '',
				//服务id，这里根据自己的设备写死
				serviceId: '',
				//特征值id-----这里根据自己的设备写死
				characteristicId: '6E400002-B5A3-F393-E0A9-E50E24DCCA9E',
				//设备名称
				deviceName: '',
				//存放蓝牙设备数组
				devices: [{
					'name': 222
				}, {
					'name': 333
				}],
				//查看是否连接
				connected: false,
				//存储当前连接状态，里面的value就是手机接收的值
				chs: [],
				//记录电脑向手机传递的数据
				myDataMeasure: [],
				//查询蓝牙适配器的开始时间
				_discoveryStarted: false,
				//是否可写
				canWrite: false,
				//要发送的数据
				sendData: '',
				//下部信息条的显示与隐藏(默认显示)
				infoShowHide: true,
				//隐藏和打开按钮的字
				infoShowHideButton: '隐藏',
				//用户对设备设置的基本参数
				myData: {
					myInterval: ''
				},
				//临时存储仪器传输的数据以及基本设置信息
				myMeatureDataPhone: [],
				//存放数据的key，等待网络好的时候通过key传递数据到服务器
				myTemplateKey: [],
				//记录存储数据的时间
				timeNow: '',
				// 骨架屏
				skeletonShow: false,
				//图表
				lineChartData: {

					label: [],
					value: [{
						name: '血糖',
						data: []
					}]

				},
				yAxisAs: {
					// disabled:false,
					max: 200,
					formatter: {
						type: 'number', //type:number percent String,额外参数:fixed:NUmber,name:String
						fixed: 0,
						name: ''
					}

				},
				canvasId: 'canvasMix',
				labelKey: 'label',
				valueKey: 'value',
				width: 750,
				height: 500,
				showEchart: false,
				showMaskloading: false,
				factory:'',//设备生产厂家
				timeObj: '',
				connStatus: -1, //蓝牙连接状态  0 未连接  1 连接中  2 已连接  8 中断连接  9 绑定用户失败  10 获取蓝牙服务失败
				//connType  reconnect  重连   create  创建蓝牙连接
				errorMsg: {
					7: {
						msg: '用户绑定设备失败',
						code: '设备已被其它用户绑定,请先解绑设备',
						connType: 'reconnect',
						src: ''
					},
					8: {
						msg: '搜索超时,检测未发现蓝牙设备...',
						code: '请确保蓝牙设备已开机,或处于连接状态',
						connType: 'create',
						src: ''
					},
					9: {
						msg: '用户绑定设备失败',
						code: '服务器繁忙,请重新连接设备',
						connType: 'create',
						src: ''
					},
					10: {
						msg: '连接蓝牙设备失败',
						code: '请打开设备,重新连接或重新获取蓝牙设备',
						connType: 'reconnect',
						src: ''
					},
					20: {
						msg: 'mol浓度值太低',
						code: 'mol浓度值太低',
						connType: 'reconnect',
						src: ''
					},
					21: {
						msg: 'mol浓度值太高',
						code: 'mol浓度值太高',
						connType: 'reconnect',
						src: ''
					},
					22: {
						msg: '测量上传失败',
						code: '测量上传失败',
						connType: 'reconnect',
						src: ''
					},
					23: {
						msg: '血液异常重新测量',
						code: '血液异常重新测量',
						connType: 'reconnect',
						src: ''
					},
					30: {
						msg: '开始测量',
						code: '请把试纸插入到机器中保持设备常亮然后使用采血笔进行采血',
						connType: 'reconnect',
						src: ''
					},
					31: {
						msg: '请往试纸滴血',
						code: '请往试纸滴血',
						connType: 'reconnect',
						src: ''
					},
					32: {
						msg: '血液已经滴下等待结果',
						code: '血液已经滴下等待结果',
						connType: 'reconnect',
						src: ''
					},
				},
				isCancel: false,
				changeDevstatus:false,//是否已选择设备 
				isGlu:false,
				isUa:false,
				isMyCuia:false,
				canvasImg:null,
				changeDevValue:0 ,//选择连接的设备值,
				device_uuid:'', //ios device_uuid
				bind_mycuid:0, //是否从设备管理跳过来绑定民康
				rebind:false,
				closeBlue:false, //取消蓝牙连接
				prefix:[], //血糖仪允许的前缀列表
				isLoaded:false,
			};
		},
		created() {
	
		},
		onHide() {
			// this.closeBluetoothAdapter()
		},
		onLoad(e) {
			if(e.bind_mycuid==1){
				this.bind_mycuid = e.bind_mycuid
			}
			this.isLoaded=true,
			this.prefix=microtechDevComm.devicePrefix,
			this.deviceId=microtechDevComm.serviceUuid
		
			 
		},
		onUnload() {
			blood.closeBluetoothAdapter()
		},
		onPullDownRefresh() {
			// setTimeout(() => {

			// 	// console.log('VUEX数据', this.myDataGlobal);
			// 	// console.log('VUEX数据时间间隔', this.myDataGlobal.myInterval);
			// 	// console.log('实际蓝牙数据', this.myData);
			// 	// console.log('实际蓝牙输入框数据', this.sendData);
			// 	uni.showToast({
			// 		title: '参数更新成功'
			// 	});
			// 	uni.stopPullDownRefresh();
			// }, 1000);
		}, //注册网络状态
		computed: {
			//获取可使用窗口高度
			windowHeight() {

				return uni.getSystemInfoSync().windowHeight + 'px'
			},
			cWidth() {
				return uni.upx2px(this.width);
			},
			cHeight() {
				return uni.upx2px(this.height);
			},
			...mapGetters(['myDataGlobal', 'netWorkType'])
		},
		watch: {
			'myDataGlobal': {
				deep: true,
				immediate: true,
				handler() {
					//监听vuex数据变化，一旦变化及时取数据
					this.myData = this.myDataGlobal;
					//获取的第一个数据就是时间间隔，后两个数据就是获取的数量（目前是不能超过99组，到时候可以考虑设置时间间隔，分开发送这两个数据）
					this.sendData = ((Number(this.myData.myInterval)) * 10).toString() + this.myData.myNumber
				}
			}
		},
		mounted() {
		},
		methods: {
			initChart() {
							
				const query = uni.createSelectorQuery().in(this);
				query.select('.f2-canvas')
				  .fields({
				    node: true,
				    size: true
				  })
				  .exec(res => {
				    const { node, width, height } = res[0]; 
				    const context = node.getContext('2d'); 
				    const pixelRatio = wx.getSystemInfoSync().pixelRatio;
				    // 高清设置
				    node.width = width * pixelRatio;
				    node.height = height * pixelRatio; 
				    const config = { context, width, height, pixelRatio };
				 
					// // 实例化chart
					const chart = new F2.Chart(config) 
					chart.legend(false)
				 
					//数据源
					chart.source(this.echartsData);
					 chart.scale('value', {
						  min: 0,
						 ticks: [ 0, 3, 6, 9 ]
					 });
					chart.line().position('date*value').color('type'); 
					chart.render();
					 
				    if (chart) {
				      this.chart = chart;
				      this.canvasEl = chart.get('el');
				    }
				  }); 
			},
			onShow(e) {
				
				// console.log(blood)
				// const ds = e.currentTarget.dataset
				// this.createBLEConnection(ds.deviceId, ds.name)
				// this.$refs['conn'].open()
				// console.log(this.$refs['conn'].$refs)

				
				// F1 OE OO O1 O4 O1 OO E4 O7 O1 O1 O1 O1 17 10 C0 11 C4
				// const buffer = new ArrayBuffer(18)
				// const dataView = new DataView(buffer)
				// dataView.setUint8(0, 0xF1)
				// dataView.setUint8(1, 0x0E)
				// dataView.setUint8(2, 0x00)
				// dataView.setUint8(3, 0x01)
				// dataView.setUint8(4, 0x04)
				// dataView.setUint8(5, 0x01)
				// dataView.setUint8(6, 0x00)
				// dataView.setUint8(7, 0xE4)
				// dataView.setUint8(8, 0x07)
				// dataView.setUint8(9, 0x01)
				// dataView.setUint8(10, 0x01)
				// dataView.setUint8(11, 0x01)
				// dataView.setUint8(12, 0x01)
				// dataView.setUint8(13, 0x17)
				// dataView.setUint8(14, 0x10)
				// dataView.setUint8(15, 0xC0)
				// dataView.setUint8(16, 0x11)
				// dataView.setUint8(17, 0xC4)
				// cosole.log(buffer)
				//console.log(parseInt('f1',16))
				// console.log(this.$service.getHeadHex(buffer,0,4))
				// const dataView = new DataView(characteristic.value)	
				// this.factory = 'mycuia'
				// this.factory = 'sinocare'
				
				// if(this.factory== 'sinocare'){
				// 	//#ifdef MP-WEIXIN
				// 	let _globalData = getApp()
				// 	let _module = uni
				// 	//#endif
					
				// 	//#ifdef APP-PLUS
				// 	let _globalData = getApp().globalData
				// 	let _module = wx
				// 	//#endif
					
					 
				// 	sdkAction.initObjDefault(_globalData, _module, {
				// 		'_appId': app.globalData.appId,
				// 		'_wxSdkKey': app.globalData.wxSdkKey
				// 	},function(res) {
				// 		console.log(333, res)
				// 		if(res){
				// 			app.globalData.sdkAccessToken = res.data.sdkAccessToken
							 
				// 		}
					
				// 	}) 
				// }
			 
				if (uni.getSystemInfoSync().platform == 'ios') {
					this.mBottom = '-34px';
				}
				
				this.getData();
			},
			getData() {
				 
				let _this = this
				var opt = {
					url: '/blutdruck_check/index',
					data: {
						product_type: 3
						// factory:_this.factory  //多个血糖厂家统一连接了所以就不能传这个参数了 因为无法分辨用户到底有没有绑定这个厂家设备
					},
					success: function(res) {
						console.log(7777)
						console.log(res)
						
						if (res.status) {
							// _this.$refs['conn'].close()
							_this.factory = res.data.factory	
							_this.data.article = res.data.article
							_this.data.userInfo = res.data.userInfo
							_this.data.check = res.data.check
							_this.echartsData = res.data.echarts.value
							_this.bindDevList = res.data.devList
							_this.bindDdevNum = res.data.bindDdevNum
						      
							if (res.data.echarts) {
								_this.showEchart = true;
								setTimeout(function(){
									_this.initChart();
								},1000)
							}
							 
							//	console.log(_this.lineChartData)
							
							//从设备管理跳过来绑定民康设备才执行
							if(_this.bind_mycuid){
								_this.searchDev();
								return 
							}

							//第一次进来如果没有连接过设备则主动弹出蓝牙搜索页面
							if (!_this.data.userInfo.bindStatus) {
								_this.searchDev();
							}
							//设备断开以后不自动连接了 改成手动点击连接
							if (_this.data.userInfo.bindStatus && _this.connected == false) {
								//console.log(1111111111)
								//自动连接蓝牙设备
								_this.autoConn(_this.data.userInfo.deviceId) 
								// _this.$refs.conn.open();
							}

						} else {

							_this.connStatus = 22
						}
						//修复在测量状态下手机黑屏在唤起屏幕是出现趋势图问题
						if((_this.connStatus == 30) || (_this.connStatus == 31) || (_this.connStatus == 32) ){
							_this.showEchart = false;
						}
					}
				};
				_this.$service.GetApi(opt)
			},
			//设备连接失败确定
			confirm() {
				this.$refs['show'].close()
				// this.$refs['show'].open()
			},
			searchDev() {
				this.showEchart = false;
				this.isCancel = false;
				this.$refs['conn'].open()//打开蓝牙搜索页面
				this.connStatus = 1
				//初始化wx蓝牙模块
				let opt = {
					success:(device)=>{
							const foundDevices = this.devices //将数据中的数组复制一份,利用动态绑定方式，不断复制最新的数组
							const idx = this.inArray(foundDevices, 'deviceId', device.deviceId)
							
						
							if (idx === -1 ) {
								this.devices.push(device); //数组里没有的的就向里面添加数据，保证没有重复[uni写法]
								// console.log('搜索到的设备组',device.name+'---'+device.deviceId+'*****'+JSON.stringify(device));
							}
					}
				}
				blood.getDevList(opt)

			},
			//为了去除重复的
			inArray(arr, key, val) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i][key] === val) {
						return i;
					}
				}
				return -1;
			},
			// ArrayBuffer转16进度字符串示例
			str2ab1() {
				const buffer = new ArrayBuffer(4)
				const dataView = new DataView(buffer)
				dataView.setUint8(0, 0xA5)
				dataView.setUint8(1, 0x56)
				dataView.setUint8(2, 0x89)
				dataView.setUint8(3, 0x56)
				return buffer
			},
			//比大小
			myMax(n1, n2) {
				return Math.max(n1, n2)
			},
			//比长度
			myLen(arr) {
				arr = arr || []
				return arr.length
			},
			//显示隐藏下部信息条
			hideShowInfo() {
				this.infoShowHide = !this.infoShowHide;
				if (this.infoShowHideButton == '隐藏') {
					this.infoShowHideButton = '打开'
				} else {
					this.infoShowHideButton = '隐藏'
				}
			},
			autoConn() {
				let _this = this 
				this.closeBlue = false
				if(!_this.showMaskloading)
				{
					_this.showMaskloading = true
					setTimeout(() => {
						if(_this.factory=='sinocare' && _this.showMaskloading && !_this.blueToothPopup){
						    _this.connStatus=10,
						    _this.blueToothPopup=true
						 }
						_this.showMaskloading = false
					}, 1000 * 30);
				}	
							 
				let data = ''
				if(_this.factory=='mycuia'){
					data = {
						factory:'mycuia',
						userInfo:this.data.userInfo,
						isSdkConn:0,
						dev:{
							//设备id
							deviceId:this.data.userInfo.deviceId,
							//服务id，这里根据自己的设备写死
							serviceId: '6E400001-B5A3-F393-E0A9-E50E24DCCA9E',
							//特征值id-----这里根据自己的设备写死
							characteristicId: '6E400003-B5A3-F393-E0A9-E50E24DCCA9E',
						}		
					}
				}else{
					data = {
						factory:'sinocare',
						userInfo:this.data.userInfo,
						isSdkConn:1,//是否是sdk连接蓝牙
						dev:{
							deviceId:this.data.userInfo.deviceId,
							deviceType:this.data.userInfo.dev_type==3?25:26,
							serviceId:'',
							characteristicId:''
						}
						 			
					}
				}
				console.log('传递的参数',data)
			 
				let obj = { 
					data:data,
					bind:async (mac)=>{
						 
						//  let _this = this
						//  this.data.userInfo.deviceId =mac
						//  const resp = await new Promise((resolve, reject) => {
						// 	 		 var opt = {
							 	// 		url: '/wifi/bindDev',
							 	// 		data: {
							 	// 			dev_type:3,
							 	// 			mac:mac,
							 	// 			factory:_this.factory
							 				
							 	// 		},
							 	// 		success: function(res) {
							 	// 			// console.log(111,res)
							 	// 			if(res.status>0){
							 	// 				 resolve(res)
							 	// 			}else{
							 	// 				res.data = {bindStatus:false}
							 	// 				resolve(res)
							 	// 			}
							 				
							 								
							 	// 		}
							 	// 	};		 
								 
									// _this.$service.GetApi(opt)
						// })	
						// // console.log(resp)	
						// return resp
					},
					success:(res)=>{
						console.log('数据入库',res)
						if(res.status==1&&res.code=='onBLECharacteristicValueChange')
						{
							this.insertData(res.data.deviceId,res.data.mol,res.data.unit,res.data.factory)
						}
		
				
					},
					fail:(res)=>{
						//取消蓝牙连接则不弹窗
						if(this.closeBlue){
							return ;
						}
						console.log(res)
						this.connStatus = res.code	
								
					 	
						if(this.connStatus==7){
							this.rebind = true;
						}		
						
						this.showMaskloading = false
						if(res.code==7||res.code==9)
						{
							this.data.userInfo.deviceId = res.data.userInfo.deviceId
						}	
						this.$refs['conn'].open()
					},
					onBLEConnectionStateChange:(res)=>{
						//取消蓝牙连接则不弹窗
						if(this.closeBlue){
							return ;
						}
						console.log('蓝牙连接状态',res)
						if (res.data.connected == false) {
							this.connected = false
							if (this.data.userInfo.bindStatus) {
								this.connStatus = 10
							} else {
								this.connStatus = 8
							}
						
						}
						if(res.data.connected==true)
						{
							this.showMaskloading = false
							this.data.userInfo.bindStatus = true
							this.connected = true
							this.connStatus = 30
							this.$refs['conn'].open()
							//根据选择的连接设备区修改自动连接设备标记值
							if(_this.changeDevstatus){
								this.updateAutoConnDev();
							}
						}
					}
				}
				blood.conn(obj)
			},
			//【点击某个蓝牙设备时】将目前你点击的设备作为对象e传递进来
			checkBind(e) {
				//设备绑定成功
				// console.log('createBLEConnection', e)
				this.isCancel = false;
				this.closeBlue = false
				const _this = this
				const ds = e.currentTarget.dataset
				if(!_this.showMaskloading)
				{
					_this.showMaskloading = true
					setTimeout(() => {
						_this.showMaskloading = false
					}, 1000 * 30);
				}	
			 
				//根据蓝牙名称设置厂家
				if(ds.name == 'BBK_BLOOD'){
					_this.factory='mycuia'
				}else if(ds.name == 'BDE_WEIXIN_TTM'){
					_this.factory='sinocare'
				}
				
			 
				//重新蓝牙搜索绑定其他设备则设置绑定状态为false
				if(ds.conn!=undefined && ds.conn=='bind'){
					this.data.userInfo.bindStatus = false;
				}
				  
				let data = ''
				if(_this.factory=='mycuia'){
					data = {
						factory:'mycuia',
						userInfo:this.data.userInfo,
						isSdkConn:0,//是否是sdk连接蓝牙
						dev:{
							//设备id
							deviceId: ds.deviceId,
							//服务id，这里根据自己的设备写死
							serviceId: '6E400001-B5A3-F393-E0A9-E50E24DCCA9E',
							//特征值id-----这里根据自己的设备写死
							characteristicId: '6E400003-B5A3-F393-E0A9-E50E24DCCA9E',
						}		
					}
				}else{
					data = {
						factory:'sinocare',
						userInfo:this.data.userInfo,
						isSdkConn:1,//是否是sdk连接蓝牙
						dev:{
							deviceId:ds.deviceId,
							deviceType:25,//三诺官方血糖设备类型
							serviceId:'',
							characteristicId:''
						}
						 			
					}
				}
				console.log('传递的参数2',data)
				console.log('factory',_this.factory)
				let obj = {
					data:data,
					bind:async (mac)=>{
						//只能绑定这两个厂家设备
						if(_this.factory!='mycuia' && _this.factory!='sinocare'){
							mac=''
						}
						
						
						 this.data.userInfo.deviceId =mac
						 const resp = await new Promise((resolve, reject) => {
									 
							 		var opt = {
							 			url: '/wifi/bindDev',
							 			data: {
							 				dev_type:3,
							 				mac:mac,
							 				factory:_this.factory
							 				
							 			},
							 			success: function(res) {
							 				// console.log(111,res)
							 				if(res.status>0){
							 					 resolve(res)
							 				}else{
							 					res.data = {bindStatus:false}
							 					resolve(res)
							 				}
							 				
							 								
							 			}
							 		};		 
								 
									_this.$service.GetApi(opt)
						})	
						// console.log(resp)	
						return resp
					},
					success:(res)=>{
						console.log(res)
						if(res.status==1&&res.code=='onBLECharacteristicValueChange')
						{
							this.insertData(res.data.deviceId,res.data.mol,res.data.unit,res.data.factory)
						}
						// if(res.status==1&&res.code==30)
						// {
						// 	this.connStatus = 30
						// 	this.$refs['conn'].open()
						// }
						
					},
					fail:(res)=>{
						//取消蓝牙连接则不弹窗
						if(this.closeBlue){
							return ;
						}
						// console.log(res)
						this.connStatus = res.code
						this.showMaskloading = false 
						
						if(this.connStatus==7){
							this.rebind = true;
						}	
						
						if(res.code==7||res.code==9)
						{
							this.data.userInfo.deviceId = res.data.userInfo.deviceId
						}
						 								 
						this.$refs['conn'].open()
															
					},
					onBLEConnectionStateChange:(res)=>{
						//取消蓝牙连接则不弹窗
						if(this.closeBlue){
							return ;
						}
						console.log(res)
						if (res.data.connected == false) {
							this.connected = false
							if (this.data.userInfo.bindStatus) {
								this.connStatus = 10
							} else {
								this.connStatus = 8
							}
						
						}
						if(res.data.connected==true)
						{
							this.showMaskloading = false
							this.data.userInfo.bindStatus = true
							this.connected = true
							this.connStatus = 30
							this.$refs['conn'].open() 
							//设置当前设备为自动连接设备
							this.updateAutoConnDev();
						}
						
					}
				}
				blood.conn(obj)
				
				
			},
			insertData(deviceId, glu, unitType,factory) {
				let _this = this
				var opt = {
					url: '/blutdruck_check/gluInsert',
					data: {
						type: 0,
						version: '1.0',
						electric: 0,
						sn: 0,
						mac: deviceId,
						glu: glu,
						unit_type: unitType,
						product_type:3,
						factory:factory
					},
					success: function(res) {
						//console.log(res)
						if (res.status) {
							_this.showEchart = true;
							_this.$refs['conn'].close()
							_this.connStatus =-1;
							//刷新数据
							_this.getData();
						} else {

							_this.connStatus = 22
						}

					}
				};
				_this.$service.GetApi(opt)
			},
			//向蓝牙设备发送一个数据（期间要进行数据转换）
			writeBLECharacteristicValue() {
				console.log('我正在发送数据【手机向蓝牙模块】');
				//向蓝牙设备发送一个0x00的16进制数据//代表内存之中的一段二进制数据
				// let buffer = new ArrayBuffer()  uni.getBLEDeviceCharacteristics(OBJECT)
				// //可以自定义复合格式的视图
				// let dataView = new DataView(buffer)
				// dataView.setUint8(0, this.sendData)
				// console.log('十六进制',this.ab2hex(buffer));
				// console.log('我正在发送数据十六进制字符串:' + this.sendData);
				let buffer = this.str2ab1()
				// console.log(buffer);
				// console.log('我正在发送数据【手机向蓝牙模块】characteristicId:' + this.characteristicId);
				// console.log('我正在发送数据【手机向蓝牙模块】deviceId:' + this.deviceId);
				// console.log('我正在发送数据【手机向蓝牙模块】serviceId:' + this.serviceId);
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					value: buffer,
					complete: (e) => {
						 
						if(!this.isAutoConn){
							 this.showEchart = false;
						}
					 
						//进入测量
						this.connStatus = 30


						//buffer本身是arraybuffer（arraybuffer要转换为16进制）
						//console.log('我正在发送数据【手机向蓝牙模块】回调',JSON.stringify(e));
						// console.log('十六进制',this.ab2str1(buffer));
						// let sixNumber=this.ab2hex(buffer);
						// console.log('二进制数组:',buffer);
						//切换特征 
						this.characteristicId = '000000F5-0001-0008-0000-0805F9B34FB0'
						// console.log('切换特征deviceId:' + this.deviceId)
						// console.log('切换特征serviceId:' + this.serviceId)
						setTimeout(() => {
							this.getBLEDeviceCharacteristics(this.deviceId, this.serviceId)
						}, 1000);

					}
				})
				// console.log(999999999999)
				//this.sendData=''
			},
			//关闭搜索
			closeBlueTooth() {
				uni.stopBluetoothDevicesDiscovery();
				// console.log("已关闭蓝牙搜索(closeBlueTooth)");
			},
			//关闭蓝牙适配器
			closeBluetoothAdapter() {
				uni.closeBluetoothAdapter();
				this._discoveryStarted = false;
				console.log("已关闭蓝牙适配器(closeBluetoothAdapter)");
				//清空蓝牙设备列表
				this.devices = []
				//  uni.showToast({
				// title: "适配器关闭成功",
				// icon: "success",
				//  });
			},
			//关闭蓝牙连接
			closeBLEConnection() {
				uni.closeBLEConnection({
					deviceId: this.deviceId
				});
				this.connected = false;
				this.chs = [];
				this.canWrite = false;
				// console.log("已关闭蓝牙连接(closeBLEConnection)");
				uni.showToast({
					title: "蓝牙连接已断开",
					icon: "success",
				});
			},
			//测量结果说明
			testResult() {
				let _this = this
				this.$refer.setVilit('/packageHealthy/pages/device/blood-glucose/test_result')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {

				}
				this.$refer.toUrl(callback, data)
				return
			},
			//更多数据
			testRecord() {
				let _this = this
				this.$refer.setVilit('/packageHealthy/pages/test_record/test_record')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					group_id: 0,
					product_type: 3
				}
				this.$refer.toUrl(callback, data)
				return
			},
			articleDetail(id) {
				let _this = this
				this.$refer.setVilit('/packageArticle/pages/healthy-article/article_detail')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					id: id
				}
				this.$refer.toUrl(callback, data)
				return
			},
			// 文章推荐
			pageArticleList() {
				let _this = this
				this.$refer.setVilit('/packageArticle/pages/healthy-article/article_list')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					product_type: 3
				}
				this.$refer.toUrl(callback, data)
				return
			},
			cancelConn() {
				this.closeBlue = true,
				this.isCancel = true;
				this.isAutoConn = false;
				this.showMaskloading = false;
				this.connected = false,
					this.connStatus = -1;
				uni.stopBluetoothDevicesDiscovery() //此时停止蓝牙搜索
				this.closeBLEConnection();
				blood.closeBluetoothAdapter();
			},
			//根据弹出层显示状态来切换画布和图片的显示
			popupChange(e){
				if(!e.show){
					this.canvasImg = null;
				}else{
					this.handleCanvarToImg();
				}
			
			},
			ChangeDev(type){
				let _this = this
				 
				if(type==4){
					_this.changeDevValue = 4
					this.isGlu = false;
					this.isUa = true;
					this.isMyCuia = false;
				}else if(type==3){
					this.isGlu = true;
					this.isUa = false;
					this.isMyCuia = false;
					_this.changeDevValue = 3
				}else if(type==2){
					this.isGlu = false;
					this.isUa = false;
					this.isMyCuia = true;
					_this.changeDevValue = 2
				}
				 
			},
			connel(){
				this.$refs.bindChangeDev.close()
			},
			showBindChangeDev(){
				this.$refs.bindChangeDev.open()
			},
			commit(){
				let _this= this
			 
			 
				if(!_this.changeDevValue){
					uni.showToast({
						title:'请选择要连接的设备',
						icon:'none'
					})
					return
				}
				 
				if(_this.changeDevValue == 4){
					_this.factory='sinocare'
					//三诺尿酸血糖仪
					_this.data.userInfo.deviceId = _this.bindDevList.sinocare[4].mac
					_this.data.userInfo.dev_type = 4
				}else if(_this.changeDevValue == 3){
					_this.factory='sinocare'
					 //三诺血糖仪
					 _this.data.userInfo.deviceId = _this.bindDevList.sinocare[3].mac
					_this.data.userInfo.dev_type =3
				}else{
					_this.factory='mycuia'
					//民康血糖仪
					_this.data.userInfo.deviceId = _this.bindDevList.mycuia.mac
				}
				console.log('选择连接的设备',_this.data.userInfo.deviceId)
			 
				_this.changeDevstatus = true
				_this.$refs.bindChangeDev.close()
			   _this.autoConn();
			},
			handleCanvarToImg() {
			   var _this=this;
							//当有弹出窗的时候讲画布转成图片替换掉画布即可
			   uni.canvasToTempFilePath({
			     canvas: _this.f2_canvas,
			     success: function(res) {
								  _this.canvasImg = res.tempFilePath
			     }
			   });
			 },
			 updateAutoConnDev(){
				 let _this = this
				 var opt = {
				 	url: '/blutdruck_check/updateAutoConnDev',
				 	data: { 
				 		sn: 0,
				 		mac: this.data.userInfo.deviceId, 
				 		factory:this.factory
				 	},
				 	success: function(res) {
				 		//console.log(res)
				 		if (res.status) { 
				 		} else {
				 
				 			 
				 		}
				 
				 	}
				 };
				 _this.$service.GetApi(opt)
			 }
		},
	};
</script>

<style lang="scss">
	@import "./index.scss";
</style>
